<template>
  <div class="dept-management-container">
    <!-- 标题与说明 -->
    <div class="description-section">
      <h2>四、科室管理</h2>
      <div class="description-content">
        <div class="desc-item">
          <strong>功能描述：</strong>
          <p>维护医院科室架构及科室属性（如是否为重点科室、是否开通急诊服务），支持科室合并、拆分及负责人变更等操作。</p>
        </div>
        <div class="desc-item">
          <strong>操作流程：</strong>
          <p>在“科室管理”界面添加新科室（如“心血管内科”），填写科室编码、上级科室、床位数量等基础信息；如需调整科室结构，可选择目标科室执行“合并至”或“拆分为”操作，系统自动更新相关业务关联。</p>
        </div>
      </div>
    </div>

    <el-card class="design-card">
      <template #header>
        <div class="card-header">
          <span>科室科别增加</span>
        </div>
      </template>

      <div class="layout">
        <!-- 左侧：科室树 -->
        <div class="left-tree">
          <el-tree
            :data="treeData"
            node-key="id"
            :props="{ label: 'label', children: 'children' }"
            highlight-current
            default-expand-all
            @node-click="handleTreeClick"
          />
        </div>

        <!-- 右侧：表单区 -->
        <div class="right-form">
          <el-form :model="deptForm" label-width="90px" class="dept-form">
            <el-form-item label="科别：">
              <el-input v-model="deptForm.category" placeholder="如 内科 / 外科" />
            </el-form-item>
            <el-form-item label="科别名称：">
              <el-input v-model="deptForm.name" placeholder="请输入科室名称" />
            </el-form-item>
            <el-form-item label="科室地址：">
              <el-input v-model="deptForm.address" placeholder="门诊楼/住院部等" />
            </el-form-item>
            <el-form-item label="挂 号 费：">
              <el-input v-model="deptForm.registrationFee" placeholder="例如 20" />
            </el-form-item>
            <div class="btn-row">
              <el-button type="primary" @click="addDepartment">添加</el-button>
              <el-button @click="clearDepartment">清除</el-button>
              <el-button type="warning" @click="modifyDepartment" :disabled="!selectedNodeId">修改科室</el-button>
            </div>
          </el-form>

          <div class="divider" />

          <!-- 疾例管理区（示例：绑定到科别） -->
          <div class="disease-section">
            <div class="section-title">病例：</div>
            <el-form :model="diseaseForm" label-width="90px">
              <el-form-item label="科别：">
                <el-select v-model="diseaseForm.departmentId" placeholder="请选择科别">
                  <el-option
                    v-for="d in flatDepartments"
                    :key="d.id"
                    :label="d.label"
                    :value="d.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="名称：">
                <el-input v-model="diseaseForm.name" placeholder="如 支气管炎" />
              </el-form-item>
              <div class="btn-row">
                <el-button type="primary" @click="addDisease">添加</el-button>
                <el-button type="danger" @click="removeDisease" :disabled="!selectedDiseaseId">删除</el-button>
                <el-button @click="clearDisease">取消</el-button>
              </div>
            </el-form>

            <el-table :data="currentDeptDiseases" size="small" class="disease-table" @row-click="(row)=>selectedDiseaseId=row.id">
              <el-table-column prop="name" label="疾病名称" />
            </el-table>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'

type TreeNode = { id: number; label: string; children?: TreeNode[] }

// 本地演示数据，可后续改成从接口加载
const treeData = ref<TreeNode[]>([
  { id: 1, label: '内科', children: [
    { id: 11, label: '心内科' },
    { id: 12, label: '呼吸内科' },
  ]},
  { id: 2, label: '外科', children: [
    { id: 21, label: '普外科' },
    { id: 22, label: '骨科' },
  ]},
  { id: 3, label: '儿科' },
  { id: 4, label: '中医科' },
])

// 展平后的科室列表（用于下拉）
const flatDepartments = computed(() => {
  const list: { id: number; label: string }[] = []
  const dfs = (nodes: TreeNode[]) => {
    nodes.forEach(n => {
      list.push({ id: n.id, label: n.label })
      if (n.children) dfs(n.children)
    })
  }
  dfs(treeData.value)
  return list
})

const selectedNodeId = ref<number | null>(null)

const deptForm = reactive({
  category: '',
  name: '',
  address: '',
  registrationFee: '',
})

const diseaseForm = reactive({
  departmentId: null as number | null,
  name: '',
})

const diseasesByDept = reactive<Record<number, { id: number; name: string }[]>>({})
const selectedDiseaseId = ref<number | null>(null)

const handleTreeClick = (node: any) => {
  selectedNodeId.value = node.id
  // 将点击节点名称填入“科别名称”
  deptForm.name = node.label
}

const clearDepartment = () => {
  deptForm.category = ''
  deptForm.name = ''
  deptForm.address = ''
  deptForm.registrationFee = ''
}

const addDepartment = () => {
  if (!deptForm.name) {
    ElMessage.warning('请输入科别名称')
    return
  }
  const newId = Date.now()
  treeData.value.push({ id: newId, label: deptForm.name })
  ElMessage.success('已添加科室')
  clearDepartment()
}

const modifyDepartment = () => {
  if (!selectedNodeId.value) return
  const updateLabel = deptForm.name
  const dfs = (nodes: TreeNode[]) => {
    nodes.forEach(n => {
      if (n.id === selectedNodeId.value) n.label = updateLabel
      if (n.children) dfs(n.children)
    })
  }
  dfs(treeData.value)
  ElMessage.success('已修改科室')
}

const currentDeptDiseases = computed(() => {
  const id = diseaseForm.departmentId ?? selectedNodeId.value ?? 0
  return diseasesByDept[id] ?? []
})

const addDisease = () => {
  if (!diseaseForm.departmentId) {
    ElMessage.warning('请选择科别')
    return
  }
  if (!diseaseForm.name) {
    ElMessage.warning('请输入疾病名称')
    return
  }
  const id = diseaseForm.departmentId
  if (!diseasesByDept[id]) diseasesByDept[id] = []
  diseasesByDept[id].push({ id: Date.now(), name: diseaseForm.name })
  ElMessage.success('已添加疾病')
  diseaseForm.name = ''
}

const removeDisease = () => {
  if (!diseaseForm.departmentId || !selectedDiseaseId.value) return
  const list = diseasesByDept[diseaseForm.departmentId]
  if (!list) return
  const idx = list.findIndex(x => x.id === selectedDiseaseId.value)
  if (idx >= 0) list.splice(idx, 1)
  selectedDiseaseId.value = null
  ElMessage.success('已删除')
}

const clearDisease = () => {
  diseaseForm.departmentId = null
  diseaseForm.name = ''
  selectedDiseaseId.value = null
}
</script>

<style scoped lang="scss">
.dept-management-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.description-section {
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  h2 {
    margin: 0 0 15px 0;
    color: #333;
    font-size: 18px;
  }
}

.design-card {
  :deep(.el-card__header) {
    padding: 15px 20px;
    background-color: #fafafa;
  }
}

.layout {
  display: grid;
  grid-template-columns: 340px 1fr;
  gap: 20px;
}

.left-tree {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: #fff;
  padding: 10px;
}

.right-form {
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 16px;
}

.btn-row {
  display: flex;
  gap: 12px;
}

.divider {
  height: 1px;
  background: #e4e7ed;
  margin: 16px 0;
}

.section-title {
  font-weight: 600;
  margin-bottom: 10px;
}

.disease-table {
  margin-top: 10px;
}
</style>


